<?php
ob_start();
session_start();
include "checksession.php";
date_default_timezone_set('Asia/Bangkok');
include("../connect.php");
$addFormAction = $_SERVER['PHP_SELF'];
$id_depart = $_GET['departid'];

if (isset($_SERVER['QUERY_STRING'])) {
  $addFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
?>
<html>
<head>
<title>Adinop Co., Ltd. was founded as an ingredients importer and local manufacturers’ distributor in 1986. We also function as an exporter of finished products</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="../js/jquery/jquery-latest.min.js"></script>
<link rel="stylesheet" href="../css/style.css"/>
</head>
<script language="JavaScript">
	   var HttPRequest = false;

	   function doCallAjax() {
		  HttPRequest = false;
		  if (window.XMLHttpRequest) { // Mozilla, Safari,...
			 HttPRequest = new XMLHttpRequest();
			 if (HttPRequest.overrideMimeType) {
				HttPRequest.overrideMimeType('text/html');
			 }
		  } else if (window.ActiveXObject) { // IE
			 try {
				HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
			 } catch (e) {
				try {
				   HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			 }
		  } 
		  
		  if (!HttPRequest) {
			 alert('Cannot create XMLHTTP instance');
			 return false;
		  }
	
		  var url = 'check_record_id.php';
		  var pmeters = "tEmployee_id=" + encodeURI( document.getElementById("txtEmployee_id").value );

			HttPRequest.open('POST',url,true);

			HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			HttPRequest.setRequestHeader("Content-length", pmeters.length);
			HttPRequest.setRequestHeader("Connection", "close");
			HttPRequest.send(pmeters);
			
			
			HttPRequest.onreadystatechange = function()
			{

				if(HttPRequest.readyState == 3)  // Loading Request
				{
					document.getElementById("mySpan").innerHTML = "..";
				}

				if(HttPRequest.readyState == 4) // Return Request
				{
					if(HttPRequest.responseText == 'Y')
					{
						window.location = 'AjaxPHPRegister3.php';
					}
					else
					{
						document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
					}
				}
				
			}

	   }
	</script>
<script language="JavaScript">
	   var HttPRequest = false;

	   function doCallAjax1() {
		  HttPRequest = false;
		  if (window.XMLHttpRequest) { // Mozilla, Safari,...
			 HttPRequest = new XMLHttpRequest();
			 if (HttPRequest.overrideMimeType) {
				HttPRequest.overrideMimeType('text/html');
			 }
		  } else if (window.ActiveXObject) { // IE
			 try {
				HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
			 } catch (e) {
				try {
				   HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			 }
		  } 
		  
		  if (!HttPRequest) {
			 alert('Cannot create XMLHTTP instance');
			 return false;
		  }
	
		  var url = 'check_record_name.php';
		  var pmeters = "tName_eng=" + encodeURI( document.getElementById("txtName_eng").value );

			HttPRequest.open('POST',url,true);

			HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			HttPRequest.setRequestHeader("Content-length", pmeters.length);
			HttPRequest.setRequestHeader("Connection", "close");
			HttPRequest.send(pmeters);
			
			
			HttPRequest.onreadystatechange = function()
			{

				if(HttPRequest.readyState == 3)  // Loading Request
				{
					document.getElementById("mySpan1").innerHTML = "..";
				}

				if(HttPRequest.readyState == 4) // Return Request
				{
					if(HttPRequest.responseText == 'Y')
					{
						window.location = 'AjaxPHPRegister3.php';
					}
					else
					{
						document.getElementById("mySpan1").innerHTML = HttPRequest.responseText;
					}
				}
				
			}

	   }
	</script>
<script type="text/javascript">
function KeyCodeInt(objId)
{
if (event.keyCode >= 48 && event.keyCode<=57) //48-57(ตัวเลข) ,65-90(Eng ตัวพิมพ์ใหญ่ ) ,97-122(Eng ตัวพิมพ์เล็ก)
{
return true;
}
else
{
alert("กรอกได้เฉพาะตัวเลข 0-9 เท่านั้นครับ");
event.returnValue = false;
}
}

function KeyCodeEng(objId)
{
if (event.keyCode>=97 && event.keyCode<=122 ) //48-57(ตัวเลข) ,65-90(Eng ตัวพิมพ์ใหญ่ ) ,97-122(Eng ตัวพิมพ์เล็ก)
{
return true;
}
else
{
alert("กรอกได้เฉพาะตัวพิมพ์เล็ก a-z");
event.returnValue = false;
}
}

function CheckThai(sText,obj){
	var ValidChars = "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬหอฮ ะา ิ ี ึ ื ุ ูฤๅฦ ์ ำ ๋ ๊ ็ ่ ้ ั โไใ เ แ '; ";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++){   
		Char = sText.charAt(i);   
		if (ValidChars.indexOf(Char) == -1){  
			IsNumber = false;
		}
	}
	if(IsNumber==false){
		alert("กรอกได้เฉพาะภาษาไทย");
		obj.value="";
	}
}
</script>
<script language="javascript">
			function CheckValidate()
			{
			if(eval("document.frmMain.txtEmployee_id.value")==""){
				alert("กรุณากรอกช่อง Employee Id");
				eval("document.frmMain.txtEmployee_id.focus();")
				return false;
				}

			if(eval("document.frmMain.txtName_eng.value")==""){
				alert("กรุณากรอกช่อง Name(ENG)");
				eval("document.frmMain.txtName_eng.focus();")
				return false;
				}

			if(eval("document.frmMain.txtSurname_eng.value")==""){
				alert("กรุณากรอกช่อง Surname(ENG)");
				eval("document.frmMain.txtSurname_eng.focus();")
				return false;
				}

			if(eval("document.frmMain.txtDepartment.value")==""){
				alert("กรุณาเลือกช่อง Department");
				eval("document.frmMain.txtDepartment.focus();")
				return false;
				}

			if(eval("document.frmMain.txtName_th.value")==""){
				alert("กรุณากรอกช่อง Name(TH)");
				eval("document.frmMain.txtName_th.focus();")
				return false;
				}

			if(eval("document.frmMain.txtSurname_th.value")==""){
				alert("กรุณากรอกช่อง Surname(TH)");
				eval("document.frmMain.txtSurname_th.focus();")
				return false;
				}

			if(eval("document.frmMain.txtUsername.value")==""){
				alert("กรุณากรอกช่อง Username");
				eval("document.frmMain.txtUsername.focus();")
				return false;
				}

			if(eval("document.frmMain.txtadmaillocal.value")==""){
				alert("กรุณากรอกช่อง admail.local");
				eval("document.frmMain.txtadmaillocal.focus();")
				return false;
				}
/*
			if(eval("document.frmMain.txtadinopcoth.value")==""){
				alert("กรุณากรอกช่อง adinop.co.th");
				eval("document.frmMain.txtadinopcoth.focus();")
				return false;
				}
*/
			if(document.frmMain.chkreq.checked == false){
				alert("กรุณาติ๊กช่อง I agree");
				document.frmMain.chkreq.focus();
				return false;
				}

			if(document.frmMain.txtName_eng.value != document.frmMain.txtUsername.value){
				alert("กรุณากรอกชื่อให้เหมือนกัน");
				document.frmMain.txtUsername.focus();
				return false;
				}
			
			if(document.frmMain.txtEmployee_id.value.length < 8){
				alert('กรุณากรอกตัวเลข 8 ตัว');
				return false;
				}
			}

</script>
<script type="text/javascript">
$(document).ready(function(){

	$("#txtEmployee_id").change(function(){

		$("#txtEmployee_id").empty();

			$.ajax({ 
				url: "returnEmployee.php" ,
				type: "POST",
				data: 'sCusID=' +$("#txtEmployee_id").val()
			})
			.success(function(result) { 

				var obj = jQuery.parseJSON(result);
				
					if(obj == '')
					{
							   $("#txtName_eng").val('');
							   $("#txtSurname_eng").val('');
							   $("#txtName_th").val('');
							   $("#txtSurname_th").val('');
							   $("#txtUsername").val('');
							   $("#txtadmaillocal").val('');
							   $("#txtadinopcoth").val('');
					}
					else
					{
						  $.each(obj, function(key, inval) {
							
							if($("#txtEmployee_id").val() == inval["id_member"]){

							   $("#txtEmployee_id").val(inval["id_member"]);
							   $("#txtName_eng").val(inval["f_name_e"]);
							   $("#txtSurname_eng").val(inval["l_name_e"]);
							   $("#txtName_th").val(inval["f_name"]);
							   $("#txtSurname_th").val(inval["l_name"]);
							   $("#txtStartdate").val(inval["date_inwork"]);
							   $("#txtUsername").val(inval["f_name_e"]);
							   $("#txtadmaillocal").val(inval["i_email"]);
							   $("#txtadinopcoth").val(inval["x_email"]);
							}else{
							   $("#txtEmployee_id").val(inval["emp_id"]);
							   $("#txtName_eng").val(inval["emp_nameEng"]);
							   $("#txtSurname_eng").val(inval["emp_surnameEng"]);
							   $("#txtName_th").val(inval["emp_nameTh"]);
							   $("#txtSurname_th").val(inval["emp_surnameTh"]);
							   $("#txtStartdate").val(inval["emp_startDate"]);
							   $("#txtUsername").val(inval["emp_nameEng"]);
							   $("#txtadmaillocal").val(inval["mail_local"]);
							   $("#txtadinopcoth").val(inval["mail_coth"]);
							}
							   $.each( $('select#txtDepartment>option') , function(){
							  if($(this).val()==inval["id"]){
								  $(this).attr("selected",true); 
							  }else{
							   $(this).attr("selected",false);
							  }
							 });

						  });
						   
					}

			});

		});
	});
</script>
<script type='text/javascript'>
function check_emaillocal(elm){
    var regex_email=/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*\@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{2,5})$/
    if(!elm.value.match(regex_email)){
		elm.value='';
        alert('รูปแบบ email ไม่ถูกต้อง example@admail.local');
    }
}
</script>
<script type='text/javascript'>
function check_emailcoth(elm){
    var regex_email=/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*\@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.([a-zA-Z]){2,5})$/
    if(!elm.value.match(regex_email)){
		elm.value='';
        alert('รูปแบบ email ไม่ถูกต้อง example@adinop.co.th');
    }
}
</script>
<body>
        <body class="body">

            <table align="center" width="90%">
                <tr>
                    <td colspan="2" class="header" >
                      <img src="../images/logo.png"> ใบทะเบียนประวัติเจ้าหน้าที่ 
                        <hr/>
                    </td>
                </tr >
              </table>

<div align="center">
<br/>
 <fieldset>
<legend class="nameTitle">ข้อมูลส่วนตัว</legend>
<form action="<? $addFormAction;?>" method="post" name ="frmMain" id="frmMain" OnSubmit="return CheckValidate();" onSubmit="return check_form(this)" />
<table width="100%" border="0" class="inputcontenttable">
  <tr>
    <th width="30%">
      <div align="right">Employee ID : </div></th>
    <th><div align="left">
      <input type="text" name="txtEmployee_id" id="txtEmployee_id" size="20" maxlength= "8" placeholder="รหัสเจ้าหน้าที่" onkeypress="KeyCodeInt()" />
	  <span id="mySpan"></span></div></th>

	  <th width="12%">
      <div align="right">Department : </div></th>
	   <td><select name="txtDepartment" id="txtDepartment" />
			<option value="" ><-- แผนกต่างๆ --></option>
			<?
			$strSQL = "SELECT * FROM depart where departid = '$id_depart' ORDER BY departid ASC";
			$objQuery = mysql_query($strSQL);
			while($objResuut = mysql_fetch_array($objQuery))
			{
				if($id_depart == $objResuut["departid"])
				{
					$sel = "selected";
				}
				else
				{
					$sel = "";
				}
			?>
			<!--<option value="<?=$objResuut["de_id"];?>"><?=$objResuut["departname"];?></option>-->
			<option value="<?=$objResuut["id"];?>" <?=$sel;?>><?=$objResuut["departname"];?></option>

			<?
			}
			?>

		  </select>
		</td>
  </tr>

  <tr>
    <th width="25%">
      <div align="right">Name(ENG) : </div></th>
    <th><div align="left">
      <input type="text" name="txtName_eng" id="txtName_eng" size="20" placeholder="ชื่อภาษาอังกฤษ" OnChange="JavaScript:doCallAjax1();" onkeypress="KeyCodeEng()" />
	  <span id="mySpan1"></span></div></th>
    </div></th>

	<th width="12%">
      <div align="right">Name(TH) : </div></th>
	  <td><input type="text" name="txtName_th" id="txtName_th" size="20" placeholder="ชื่อภาษาไทย" onkeyup="CheckThai(this.value,this)" /></td>
  </tr>

  <tr>
    <th width="25%">
      <div align="right">Surname(ENG) : </div></th>
    <th><div align="left">
      <input type="text" name="txtSurname_eng" id="txtSurname_eng" size="20" placeholder="นามสกุลภาษาอังกฤษ" onkeypress="KeyCodeEng()" />
    </div></th>

	<th width="12%">
      <div align="right">Surname(TH) : </div></th>
	  <td><input type="text" name="txtSurname_th" id="txtSurname_th" size="20" placeholder="นามสกุลภาษาไทย" onkeyup="CheckThai(this.value,this)"/></td>
  </tr>

  <tr>
    <th width="25%"> 
	<div align="right">Start Date : </div></th>
    <th width="236"><div align="left">
	<? date_default_timezone_set('Asia/Bangkok'); ?>
      <input type="text" name="txtStartdate" id="txtStartdate" size="20" value="<?=date("Y-m-d H:i:s"); ?>" readonly="" />
    </div></th>
    </tr>

	<tr>
    <th width="25%">
      <div align="right">Username : </div></th>
    <th><div align="left">
      <input type="text" name="txtUsername" id="txtUsername" size="20" placeholder="ชื่อภาษาอังกฤษ" onkeypress="KeyCodeEng()"/>

	  <th width="12%">
      <div align="right">Remark : </div></th>
	  <td><textarea name="txtRemark" id="txtRemark" rows="number" cols="number" wrap="off" placeholder="หมายเหตุ"/></textarea></td>
  </tr>

  <tr>
    <th width="25%" align="right">
	  <div align="right">admail.local : </div></th>
    <th><div align="left">
	  <input type="text" name="txtadmaillocal" id="txtadmaillocal" size="20" placeholder="example@admail.local" onblur='check_emaillocal(this)'/>
    </div></th>

	<th width="12%">
      <div align="right">adinop.co.th : </div></th>
	  <td><input type="text" name="txtadinopcoth" id="txtadinopcoth" size="20" placeholder="example@adinop.co.th" onblur='check_emailcoth(this)'/></td>
  </tr>
  <input type="hidden" name="txtiddepart" id="txtiddepart" size="20" value="<?=$id_depart; ?>" />
  </tr>
</table>
<br/>
<input type="checkbox" name="chkreq" id="chkreq" value="Accept" />I agree
 </fieldset>
<br/>
<input name="btnRecordadd" type="submit" id="btnRecordadd" value="สมัครสมาชิก" style="height: 30px; width: 120px" />
</form>
</div>
</body>
  <? 
	  if(isset($_POST['btnRecordadd'])){
	  $txtEmployee_id = $_POST['txtEmployee_id'];
	  $txtName_eng = $_POST['txtName_eng'];
	  $txtSurname_eng = $_POST['txtSurname_eng'];	  
	  $txtStartdate = $_POST['txtStartdate'];
//	  $txtDepartname = $_POST['txtDepartname'];
	  $txtDepartment = $_POST['txtDepartment'];
	  $txtName_th = $_POST['txtName_th'];
	  $txtSurname_th = $_POST['txtSurname_th'];
	  $txtUsername = $_POST['txtUsername'];
	  $txtadmaillocal = $_POST['txtadmaillocal'];
	  $txtadinopcoth = $_POST['txtadinopcoth'];
	  $txtRemark = $_POST['txtRemark'];
	  $chkreq = $_POST['chkreq'];
	  $txtdatetimereq = $_POST['txtdatetimereq'];
	  $sessionuserid = $_SESSION["UserID"];

	  
	  $sql = "select * from employee where emp_id = '$txtEmployee_id' and de_id = '$txtDepartment' ";
	  $query_id = mysql_query($sql);
	  if(mysql_num_rows($query_id) > 0){

		$sql1 = "update employee set emp_nameEng= '$txtName_eng' , emp_surnameEng= '$txtSurname_eng' , emp_nameTh='$txtName_th', emp_surnameTh='$txtSurname_th', de_id='$txtDepartment', cn_id='' , status = 'Y' where emp_id ='$txtEmployee_id' ";
		$rsUpdate=mysql_query($sql1);

		$sql2 = "update mail set mail_username='$txtUsername', mail_local='$txtadmaillocal', mail_coth='$txtadinopcoth', mail_remark='$txtRemark', mail_request='$chkreq', mail_requestDate=SYSDATE(), mail_authorized='', mail_authorizedDate='', mail_requestUser='', mail_requestUserDate='', mail_staffIT='', mail_staffITdate='', mail_authorizedCon='', mail_authorizedConDate='', mail_supervisor='', mail_supervisorDate='' where emp_id='$txtEmployee_id' ";
		$rsUpdate2=mysql_query($sql2);
	
	   if($rsUpdate2){
		echo "<script language='javascript'>
			   alert('Update Complete');
			   setTimeout(\"parent.$.fancybox.close()\",1000); 
			  </script>";
		 exit();
		}
				
		}
	
?>
<?	  
		$sqldepart = "select departname from depart where de_id = '$txtDepartment' ";
		$query_departname = mysql_query($sqldepart);
		while ($objResult = mysql_fetch_array($query_departname)) {
				$txtDepartname = $objResult['departname'];
		}

?>
<?
		//ถ้าไม่ได้ให้ปลี่ยนไปใช้ $sqlNo = "select MAX(emp_no13u) as emp_no13u from employee";
		$sqlNo = "select * from employee order by emp_no13u asc ";
		$query_No = mysql_query($sqlNo);
		while ($objResult_no = mysql_fetch_array($query_No)) {
				$emp_no = $objResult_no['emp_no13u'];
				$emp_no = $emp_no+1;
		}


	   $sql1 = "INSERT INTO employee (emp_id , emp_nameEng , emp_surnameEng , emp_startDate , emp_nameTh , emp_surnameTh , emp_no13u ,emp_createDate , de_id , cn_id, status) VALUES ('$txtEmployee_id','$txtName_eng','$txtSurname_eng','$txtStartdate','$txtName_th','$txtSurname_th','$emp_no','$txtStartdate','$txtDepartment','','Y')";
	   $query_id1 = mysql_query($sql1);

	    $sql2 = "INSERT INTO  `db_itmanager`.`mail` (`mail_id` ,`emp_id` ,`mail_username` ,`mail_local` ,`mail_coth` ,`mail_remark` ,`mail_request` ,`mail_requestDate` ,`mail_authorized` ,`mail_authorizedDate` ,`mail_requestUser` ,`mail_requestUserDate` ,`mail_staffIT` ,`mail_staffITdate` ,`mail_authorizedCon` ,`mail_authorizedConDate` ,`mail_supervisor` ,`mail_supervisorDate`) VALUES ('',  '$txtEmployee_id',  '$txtUsername', '$txtadmaillocal',  '$txtadinopcoth',  '$txtRemark',  '$chkreq',  SYSDATE(),  '',  '',  '',  '',  '',  '',  '',  '',  '',  '')";
	    $query_id2 = mysql_query($sql2);

	   if($query_id1){
		echo "<script language='javascript'>
			   alert('Insert Complete');
			   setTimeout(\"parent.$.fancybox.close()\",1000); 
			  </script>";
		 echo "<meta http-equiv='refresh' content='1; url=recordadd.php'>";
	   }
}  
	 
?>
</html>